package org.company.earth.spring;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

import org.company.earth.service.IScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Component;

@Component
public class PeriodSchedule {
    
    @Autowired
    @Qualifier("taskScheduler")
    private TaskScheduler schedulePool;
    
    public Map<Integer, ScheduledFuture<?>> map = new HashMap<Integer, ScheduledFuture<?>>();
    
    private class ScheduleTask implements Runnable{
        
        private IScheduleService task;
        
        public ScheduleTask(IScheduleService task) {
            this.task = task;
        }
        
        @Override
        public void run() {
            if(task.call()){
                cancel(task);
            }
        }
    }
    
    public void cancel(IScheduleService task) {
        synchronized (map) {
            ScheduledFuture<?> future = map.get(task.hashCode());
            if(future == null)
                return;
            future.cancel(true);
            map.remove(task.hashCode());
        }
    }
    
    
    public void scheduleAtFixedRate(IScheduleService task,int period) {
        synchronized (map) {
            ScheduledFuture<?> future =  schedulePool.scheduleAtFixedRate(new ScheduleTask(task), period);
            map.put(task.hashCode(), future);
        }
    }
    
    public void scheduleWithFixedDelay(IScheduleService task,int period) {
        synchronized (map) {
            ScheduledFuture<?> future =  schedulePool.scheduleWithFixedDelay(new ScheduleTask(task), period);
            map.put(task.hashCode(), future);
        }
    }
}
